<!--
 * @Author: Bobby
 * @Date: 2022-03-02 17:30:47
 * @LastEditTime: 2022-03-17 16:07:28
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\components\preview.vue
 * @CIMC-V2
-->
<template>
  <div :class="{ 'h-full': hasPda, 'master-preview': true }">
    <VePreview :dev="false" :loading="loadingPage" :page-data="getNowPageData" />
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import { eventTask } from '@ve/eventTask/index'
  import VePreview from '@/ve/layout/preview/vePreview'
  import { PreviewMixin } from '@ve/mixin'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import { deleteItems } from '@ve/utils/extendData'
  import { extendPower } from '@/ve/utils/extendData'
  import { componentId } from '@/utils/unique'
  import { extendLanguage } from '@ve/utils/translateTools'
  import { isArray } from '@/utils/validate'
  import dayjs from 'dayjs'
  import { ungzip } from '@/utils/gzip.js'
  export default defineComponent({
    name: 'Preview',
    components: { VePreview },
    mixins: [PreviewMixin],
    provide() {
      return {
        development: false,
        previewPageId: () => {
          return this.pageId
        },
      }
    },
    props: {
      menuId: {
        type: String,
        default: function () {
          return ''
        },
      },
    },
    data() {
      return {
        hasOnLoad: false,
        loadingPage: false,
        pageId: '', //当前page _id
        hasPda: process.env.VUE_APP_BuildProject === 'pda',
        info: {},
      }
    },
    computed: {
      getNowPageData() {
        let pageData = this.$store.getters['preview/getPageData'](this.pageId)
        if (pageData.data) {
          pageData.data.requestData = this.$route.query
        }
        return pageData
      },
      getVisitedRoutes() {
        return this.$store.getters['tabs/visitedRoutes']
      },
      getLanguage() {
        return this.$store.getters['user/language']
      },
      getRequestData() {
        // 获取页面的 requestData
        return this.getNowPageData?.data?.requestData
      },
      isMobile() {
        return process.env.VUE_APP_BuildProjectType === 'mobile' || this.$store.state.diy.settings.mode == 'mobile'
      },
      vuiComponents() {
        return this.$store.getters['preview/getPageModuleRefs']
      },
    },
    watch: {
      // '$route.path': function (newVal, oldVal) {
      //   console.log('bb', newVal, oldVal, this.pageId)
      // },
      // $route(to, from) {
      //   console.log('bb', to, from)
      // },
      getNowPageData() {
        if (!this.hasOnLoad && this.getHasPreview) {
          if (!this.isMobile) {
            this.onLoad()
            this.hasOnLoad = true
          }
        }
      },
      getRequestData: {
        // deep: true,
        handler() {
          // 当页面的requestData变化时重新执行一次 onLoad 事件
          const paths = this.$store.getters['preview/getPaths']
          if (paths[this.$route.path] === this.getNowPageData._id) {
            // 如果当前路由是跳转至当前页面 则执行当前页面的操作
            if (!this.isMobile) {
              this.onLoad()
            }
          }
        },
      },
    },
    mounted() {},
    activated() {
      if (!isEmpty(this.pageId)) {
        this.setNowPageId()
      }
    },
    created() {
      this.$store.dispatch('tmp/setPageLoading', true)
      this.$store.dispatch('preview/setDev', false)
      this.$store.dispatch('preview/setHasPreview', true)
      // console.log('进入Preview', this.menuId, GFCD('wms'))
      this.requestData()
    },
    methods: {
      //加载
      onLoad() {
        this.runEventTask('onLoad')
      },
      //进入事件任务 单个模块
      runEventTask(type) {
        if (type && this.getNowPageData.interaction && this.getNowPageData.interaction.length > 0) {
          console.log('页面-调用事件任务-预览-src\\components\\preview.vue', this)
          this.info = this.getNowPageData
          eventTask(this, type, this.getNowPageData)
        }
        setTimeout(() => {
          this.$store.dispatch('tmp/setPageLoading', false)
        }, 1000)
      },
      setNowPageId() {
        if (this.pageId) {
          this.$store.dispatch('preview/setNowPageId', this.pageId)
        }
      },
      //模拟1s后获取数据
      requestData() {
        this.loadingPage = true
        const APP_CODE = this.$store.getters['user/appCode']
        let _fileConfig = GFCD('dams')
        let _method = 'roleServiceImpl.queryUserRolePageJson'
        request({
          url: `${_fileConfig.domain}${_fileConfig.baseUrl}`,
          method: 'POST',
          data: { data: JSON.stringify({ MENU_CODE: this.menuId, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, APP_CODE: APP_CODE }), method: _method },
        }).then(async (res) => {
          if (res && res.data && res.data.length > 0) {
            let pageJson = ungzip(res.data[0].PAGE_JSON) || {}

            // let roleJson = res.data[0].ROLE_PAGE_JSON ? JSON.parse(res.data[0].ROLE_PAGE_JSON) : []
            let roleAllJson = []
            res.data.forEach((r) => {
              if (r.ROLE_PAGE_JSON) {
                roleAllJson = roleAllJson.concat(JSON.parse(r.ROLE_PAGE_JSON))
              }
            })
            let roleJson = [...new Set(roleAllJson)]
            console.log(JSON.parse(JSON.stringify(pageJson)))
            if (this.getLanguage != 'zh_CN') {
              let jsonList = []
              if (res.data.length > 1) {
                jsonList = ungzip(res.data[1].PAGE_JSON) || []
              } else {
                jsonList = ungzip(res.data[0].PAGE_JSON) || []
              }
              console.log('pageJson===', JSON.parse(JSON.stringify(jsonList)))
              if (isArray(jsonList)) {
                extendLanguage(pageJson, jsonList)
              }
            }
            console.log('pageJson===', JSON.parse(JSON.stringify(pageJson)))
            if (Object.keys(pageJson).length > 0) {
              if (process.env.VUE_APP_BuildProjectType === 'mobile') {
                // 如果是PDA系统 则不做权限验证筛选
                this.pageId = pageJson._id
                this.getDataFollowUp(pageJson)
              } else {
                this.pageInit(extendPower(pageJson, roleJson), roleJson)
              }
            } else {
              let emptyPage = {
                _id: `page_${componentId(6)}`,
                name: '新页面',
                type: 1,
                list: [],
                pageModules: [
                  {
                    _id: 'uiText_jem2tj',
                    VERSION: '20220408',
                    type: 'uiText',
                    name: '文本组件',
                    icon: 'link',
                    extension: {
                      textContent: {
                        type: 'exInput',
                        name: '文字内容',
                        value: '暂无拖拽内容',
                        tooltip: '',
                      },
                      fontSize: {
                        type: 'exInput',
                        name: '文字大小',
                        value: '20px',
                        tooltip: '文字大小以px为单位',
                      },
                      fontWeight: {
                        type: 'exSelect',
                        name: '字体粗细',
                        value: 'font-extrabold',
                        options: [
                          {
                            value: 'font-thin',
                            label: '默认',
                          },
                          {
                            value: 'font-extralight',
                            label: '200',
                          },
                          {
                            value: 'font-light',
                            label: '300',
                          },
                          {
                            value: 'font-normal',
                            label: '400',
                          },
                          {
                            value: 'font-medium',
                            label: '500',
                          },
                          {
                            value: 'font-semibold',
                            label: '600',
                          },
                          {
                            value: 'font-bold',
                            label: '700',
                          },
                          {
                            value: 'font-extrabold',
                            label: '800',
                          },
                          {
                            value: 'font-black',
                            label: '900',
                          },
                        ],
                      },
                      textAlign: {
                        type: 'exSelect',
                        name: '对齐方式',
                        value: 'text-center',
                        options: [
                          {
                            value: 'text-left',
                            label: '左',
                          },
                          {
                            value: 'text-center',
                            label: '中',
                          },
                          {
                            value: 'text-right',
                            label: '右',
                          },
                          {
                            value: 'text-justify',
                            label: 'justify',
                          },
                        ],
                      },
                      padding: {
                        type: 'exInputNumber',
                        name: '内边距',
                        value: 5,
                        min: 0,
                        max: 12,
                      },
                      underline: {
                        type: 'exSwitch',
                        name: '有无下划线',
                        value: false,
                        tooltip: '',
                      },
                    },
                    interaction: [],
                    logicInstruction: [],
                  },
                ],
                data: { formData: {}, requestData: {} },
                interaction: [],
                showSubPageId: '',
                hasSubPageShow: false,
                subPage: { info: {}, dialog: {}, dialogWidth: '800px', dialogHeight: '400px', clickToClose: false },
                hasMainPage: true,
                TIMECODE: `${dayjs().format('YYYY-M-D HH:mm:ss')}`,
              }
              this.pageId = emptyPage._id
              this.getDataFollowUp(emptyPage)
            }
          }
        })
      },
      getDataFollowUp(pageData) {
        console.log(pageData)
        this.$store.dispatch('preview/setPageData', pageData)
        //set page id
        this.$store.dispatch('preview/setNowPageId', pageData._id)
        this.$store.dispatch('preview/setPagesMods', pageData._id)
        //设置缓存页面 定制化用
        this.$store.dispatch('preview/setPageCaches', pageData)

        // 读取页面所有组件并记录
        // this.$store.dispatch('pageModulesState/setPageModulesState', pageData)
        if (!this.isMobile) {
          this.$store.dispatch('pageModulesState/setPageModulesStates', { pageId: this.$store.getters['preview/getNowPageId'], pageState: pageData })
        }

        this.loadingPage = false

        //获取menuid对应的path
        console.log('进入到程序')
        let _route = this.getVisitedRoutes.find((v) => v.name == this.menuId)
        this.$store.dispatch('preview/setPathsData', {
          key: _route && _route.path,
          value: pageData._id,
        })
      },
      forPageInfo(list) {
        list.forEach((v) => {
          if (!v.subPage.dialog) {
            v.subPage['dialog'] = {}
          }
          if (v.list.length > 0) {
            this.forPageInfo(v.list)
          }
        })
      },
      pageInit(pageData, roleJson) {
        this.pageId = pageData._id

        this.forPageInfo([pageData])
        //删除无权限的数据
        pageData = deleteItems(pageData, roleJson)
        console.log(pageData, 'pageData---------------------------')

        this.getDataFollowUp(pageData)
      },
    },
  })
</script>

<style lang="scss">
  @import '@ve/styles/ve.scss';
</style>
